package com.silverhaze.diamond.client.ui.table.model;

import com.silverhaze.diamond.common.entity.Detail;
import com.silverhaze.diamond.common.entity.Service;
import com.silverhaze.diamond.client.data.dao.DAOLocator;
import com.silverhaze.diamond.client.ui.UIStringConstants;
import com.silverhaze.commons.db.datasource.DataSourceAction;
import com.silverhaze.commons.db.datasource.DataSourceListener;
import com.silverhaze.diamond.client.utils.db.ServiceDataSource;

import java.util.List;

/**
 * Author: Ivan Babanin
 * Time: 20:26:30
 * Date: 20.05.2008
 * <p/>
 * This part of code is strictly confidential.
 */
public class DetailsTableModel extends AbstractServiceTableModel<Detail> {
    private List<Detail> dataList;
    private static final int colCount = 2;
    public static final int VIEW_USAGES_COLUMN = 3;

    public static final int ID = 0;

    public DetailsTableModel() {
        fillData(DAOLocator.getInstance().getDetails());
        ServiceDataSource.getInstance().addDataSourceListener(new DataSourceListener<Service>() {
            public void valuesUpdated(Class<Service> clazz, List<Service> values, DataSourceAction action) {
                if (clazz.equals(Detail.class)) {
                    refreshModelAll();
                }
            }
        });
    }

    public Detail getObjectAtRow(int row) {
        return dataList.get(row);
    }

    public int getRowCount() {
        if (dataList != null) {
            return dataList.size();
        }

        return 0;
    }

    public void fillData(List newData) {
        if (newData != null) {
            this.dataList = newData;
            setData(new Object[newData.size()][colCount]);

            Object[][] data = getData();
            for (int i = 0; i < newData.size(); i++) {
                Detail newDetail = (Detail) newData.get(i);

                data[i][0] = newDetail.getName();
                data[i][1] = newDetail.getDescription();
            }
        }
    }

    protected void createFields() {
        setColCountSize(colCount);
        setColumnName(new String[]{
                UIStringConstants.DETAIL,
                UIStringConstants.DESCRIPTION,
        });
    }

    public void refreshModelAll() {
        fillData(DAOLocator.getInstance().getDetails());
        refreshModel();
    }
}

